<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form inline :model="queryParams" class="mb-3">
      <el-form-item label="患者姓名">
        <el-input v-model="queryParams.userName" placeholder="请输入患者姓名" clearable style="width: 200px"
          @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item label="医生姓名">
        <el-input v-model="queryParams.doctorName" placeholder="请输入医生姓名" clearable style="width: 200px"
          @keyup.enter.native="handleQuery"></el-input>
      </el-form-item>
      <el-form-item label="预约时间">
        <el-date-picker v-model="dateRange" type="datetimerange" range-separator="至" start-placeholder="开始时间"
          end-placeholder="结束时间" value-format="yyyy-MM-dd HH:mm:ss" unlink-panels></el-date-picker>
      </el-form-item>
      <el-form-item label="预约状态">
        <el-select v-model="queryParams.appointmentStatus" placeholder="请选择预约状态" clearable style="width: 200px">
          <el-option v-for="dict in dict.type.appointment_status" :key="dict.dictValue" :label="dict.dictLabel"
            :value="dict.dictValue"></el-option>
        </el-select>
      </el-form-item>
      <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
      <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
    </el-form>

    <!-- 预约信息列表 -->
    <el-table :data="tableData" border v-loading="loading" style="width: 100%">
      <el-table-column type="index" label="序号" width="50" align="center"></el-table-column>
      <el-table-column prop="userName" label="患者姓名" align="center">
        <template slot-scope="scope">
          <span v-if="!scope.row.userName">
            暂无用户预约
          </span>
          <span v-else>
            {{ scope.row.userName }}
          </span>
        </template>
      </el-table-column>
      <el-table-column prop="doctorName" label="医生姓名" align="center"></el-table-column>
      <el-table-column prop="appointmentTime" label="预约时间" align="center">
        <template slot-scope="scope">{{ parseTime(scope.row.appointmentTime) }}</template>
      </el-table-column>
      <el-table-column prop="appointmentDuration" label="就诊时长(分钟)" align="center"></el-table-column>
      <el-table-column label="预约状态" align="center">
        <template slot-scope="scope">
          {{ selectDictLabel(dict.type.appointment_status, scope.row.appointmentStatus) }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleViewDetail(scope.row)">
            查看详情
          </el-button>
          <el-button type="text" size="small" @click="deleteHandler(scope.row)" v-show="scope.row.userName">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
      :current-page="queryParams.pageNum" :page-sizes="[10, 20, 30, 50]" :page-size="queryParams.pageSize"
      :total="total" layout="total, sizes, prev, pager, next, jumper" class="mt-3"></el-pagination>

    <!-- 详情弹窗 -->
    <el-dialog title="预约详情" :visible.sync="detailVisible" width="60%" :close-on-click-modal="false">
      <el-descriptions border>
        <el-descriptions-item label="患者姓名">
          <span v-if="!detail.userName">
            暂无用户预约
          </span>
          <span v-else>
            {{ detail.userName }}
          </span>
        </el-descriptions-item>
        <el-descriptions-item label="医生姓名">{{ detail.doctorName }}</el-descriptions-item>
        <el-descriptions-item label="预约时间">{{ parseTime(detail.appointmentTime) }}</el-descriptions-item>
        <el-descriptions-item label="预约时长">{{ detail.appointmentDuration }} 分钟</el-descriptions-item>
        <el-descriptions-item label="预约状态">
          {{ selectDictLabel(dict.type.appointment_status, detail.appointmentStatus) }}
        </el-descriptions-item>
      </el-descriptions>
      <div slot="footer" class="dialog-footer">
        <el-button @click="detailVisible = false">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getAppointmentList, deleteAppointment } from '@/api/appointment/appointment'

export default {
  name: 'AppointmentManagement',
  dicts: ['appointment_status'], // 注入预约状态字典
  data() {
    return {
      tableData: [],
      total: 0,
      loading: false,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: '',
        doctorName: '',
        appointmentStatus: null,
        startTime: null,
        endTime: null
      },
      dateRange: [],
      detailVisible: false,
      detail: {}
    }
  },
  created() {
    this.loadAppointmentData()
  },
  methods: {
    // 加载预约数据
    loadAppointmentData() {
      this.loading = true
      // 处理日期范围
      if (this.dateRange && this.dateRange.length === 2) {
        this.queryParams.startTime = this.dateRange[0]
        this.queryParams.endTime = this.dateRange[1]
      } else {
        this.queryParams.startTime = null
        this.queryParams.endTime = null
      }

      getAppointmentList(this.queryParams).then(response => {
        this.tableData = response.rows || []
        this.total = response.total || 0
        this.loading = false
      }).catch(error => {
        this.loading = false
        this.$message.error('加载预约信息失败：' + (error.message || '未知错误'))
      })
    },

    // 查询按钮
    handleQuery() {
      this.queryParams.pageNum = 1
      this.loadAppointmentData()
    },

    // 重置按钮
    handleReset() {
      this.queryParams.userName = ''
      this.queryParams.doctorName = ''
      this.queryParams.appointmentStatus = null
      this.dateRange = []
      this.queryParams.startTime = null
      this.queryParams.endTime = null
      this.handleQuery()
    },

    // 分页方法
    handleSizeChange(size) {
      this.queryParams.pageSize = size
      this.loadAppointmentData()
    },
    handleCurrentChange(page) {
      this.queryParams.pageNum = page
      this.loadAppointmentData()
    },
    // 查看详情
    handleViewDetail(row) {
      this.detail = { ...row }
      this.detailVisible = true
    },
    deleteHandler(row) {
      console.log(row);
      this.$confirm(
        '此操作将永久删除该预约记录，是否继续？',
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        deleteAppointment({ appointmentId: row.appointmentId }).then(response => {
          this.$message.success('预约记录删除成功！')
          this.loadAppointmentData()
        }).catch(error => {
          this.$message.error('删除失败：' + (error.message || '服务器异常，请稍后重试'))
        })
      }).catch(() => {
        this.$message.info('已取消删除操作')
      })
    }
  }
}
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.dialog-footer {
  text-align: center;
}
</style>
